﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using ALS.Communication.Contract.Enums;
using ALS.Communication.Domain.Adapters;
using ALS.Component.Data;
using ALS.Component.Tools.AsyncTcp;
using ALS.Component.Tools.Helpers;
using ALS.IRepository;
using ALS.Poco;

namespace ALS.Communication.Domain.Services
{
    /// <summary>
    /// 异步Tcp领域服务
    /// </summary>
    public class AsyncTcpService
    {
        /// <summary>
        /// 控制板仓储
        /// </summary>
        [Import(typeof(IDashboardRepository))]
        protected IDashboardRepository dashboardRepository { get; set; }

        /// <summary>
        /// Tcp服务器仓储
        /// </summary>
        [Import(typeof(ITcpServerRepository))]
        protected ITcpServerRepository tcpServerRepository { get; set; }

        /// <summary>
        /// 输送带仓储
        /// </summary>
        [Import(typeof(IConveyorRepository))]
        protected IConveyorRepository conveyorRepository { get; set; }

        /// <summary>
        /// 自动物流工人仓储
        /// </summary>
        [Import(typeof(IAlsWorkerRepository))]
        protected IAlsWorkerRepository alsWorkerRepository { get; set; }

        /// <summary>
        /// 吐货嘴仓储
        /// </summary>
        [Import(typeof(IShippingPortRepository))]
        protected IShippingPortRepository shippingPortRepository { get; set; }

        /// <summary>
        /// Als工作单元
        /// </summary>
        [Import("AlsUnitOfWork", typeof(IUnitOfWork))]
        protected IUnitOfWork AlsUnitOfWork { get; set; }

        private AsyncTcpServer asyncTcpServer;

        public AsyncTcpService()
        {
            asyncTcpServer = new AsyncTcpServer(ConfigHelper.GetAppSetting<int>("Port"));
            asyncTcpServer.ClientConnected += new EventHandler<TcpClientConnectedEventArgs>((sender, e) =>
            {
                var dashboard = dashboardRepository.Entities.FirstOrDefault(d => d.IPAddress.Equals(e.TcpClient.Client.RemoteEndPoint.ToString()));
                if (dashboard != null)
                {
                    //WRITE LOG
                }
                
            });

            asyncTcpServer.ClientDisconnected += new EventHandler<TcpClientDisconnectedEventArgs>((sender, e) =>
            {
                var dashboard = dashboardRepository.Entities.FirstOrDefault(d => d.IPAddress.Equals(e.TcpClient.Client.RemoteEndPoint.ToString()));
                if (dashboard != null)
                {
                    //WRITE LOG
                }
            });

            asyncTcpServer.DatagramReceived += new EventHandler<TcpDatagramReceivedEventArgs<byte[]>>((sender, e) =>
            {
                if (e.Datagram.Length > 4)
                {
                    var header = e.Datagram.First();
                    var cmd = e.Datagram.Skip(1).First();
                    var address = e.Datagram.Skip(2).First();
                    var body = e.Datagram.Skip(3).Take(e.Datagram.Length - 4);
                    var foot = e.Datagram.Last();

                    if (header == 0x68 && foot == 0xff)
                    {
                        var adapter = AdapterFactory.GetAdapter((CommendTypeEnum)cmd);
                        adapter.Process(body, asyncTcpServer, e.TcpClient);
                    }
                }
            });
        }

        ~AsyncTcpService()
        {
            asyncTcpServer.Stop();
        }

        /// <summary>
        /// 启动Tcp服务器
        /// </summary>
        public void TcpServerStart()
        {
            if (!asyncTcpServer.IsRunning)
            {
                asyncTcpServer.Start();
            }
        }

        /// <summary>
        /// 服务是否正在运行
        /// </summary>
        /// <returns></returns>
        public bool IsRunning()
        {
            return asyncTcpServer.IsRunning;
        }

        /// <summary>
        /// Tcp服务停止
        /// </summary>
        public void TcpServerStop()
        {
            asyncTcpServer.Stop();
        }

        ///// <summary>
        ///// Tcp客户端连接
        ///// </summary>
        //public void TcpClientConnection()
        //{
        //    AsyncTcpClient.Instance.ServerExceptionOccurred += new EventHandler<TcpServerExceptionOccurredEventArgs>((sender, e) =>
        //    {
        //        Console.WriteLine(e.Exception.Message);
        //    });
        //    AsyncTcpClient.Instance.ServerConnected += new EventHandler<TcpServerConnectedEventArgs>((sender, e) =>
        //    {
        //        Console.WriteLine("Connected," + e.Addresses[0].ToString() + e.Port);
        //    });
        //    AsyncTcpClient.Instance.ServerDisconnected += new EventHandler<TcpServerDisconnectedEventArgs>((sender, e) =>
        //    {
        //        Console.WriteLine("DisConnected" + e.Addresses[0].ToString() + e.Port);
        //    });
        //    AsyncTcpClient.Instance.PlaintextReceived += new EventHandler<TcpDatagramReceivedEventArgs<string>>((sender, e) =>
        //    {
        //        Console.WriteLine("Send:" + e.Datagram);
        //    });
        //    AsyncTcpClient.Instance.Connect();
        //}

        //public void TcpClientSend(string text)
        //{
        //    try
        //    {
        //        AsyncTcpClient.Instance.Send(text);
        //    }
        //    catch (Exception ex)
        //    {
        //        Console.WriteLine(ex.Message);
        //    }
        //}
    }
}
